<template>
  <div class="comment-container">
    <h1 class="title">发表评论</h1>
    <textarea placeholder="请输入要评论的内容（最多120个字）" maxlength="120" v-model="commentText"></textarea>
    <mt-button type="primary" size="large" @click="sendComment">发表评论</mt-button>
    <ul class="comment-list">
      <li v-for="(item,index) in commemtList" :key="index">
        <div class="comment-title">
          <span>第{{index + 1 }}楼：</span>&nbsp;&nbsp;
          <span>用户:{{item.user_name}}</span>&nbsp;&nbsp;
          <span>发表时间:{{item.add_time | dateFormat()}}</span>
        </div>
        <div class="comment-body">
          {{item.content === "underfind" || item.content === "" ? "此用户太懒，什么也没留下":item.content}}
        </div>
      </li>
    </ul>
    <mt-button plain size="large" type="danger" @click="more">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from "mint-ui"; // 因为 Toast 不是一个全局的变量，所以全局注册无效，要局部引入
export default {
  data() {
    return {
      pageindex: 1,
      commemtList: [],
      commentText: ""
    };
  },
  created() {
    this.getComment();
  },
  methods: {
    getComment() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageindex)
        .then(result => {
          if (result.body.status === 0) {
            // 连接评论的数组 concat() 连接数组
            this.commemtList = this.commemtList.concat(result.body.message);
            console.log(this.commemtList);
          }
        });
    },
    more() {
      this.pageindex++;
      this.getComment();
    },
    sendComment() {
      if (this.commentText.trim().length === 0) {
        return Toast("评论不能为空！");
      }
      this.$http
        .post("api/postcomment/" + this.id, {
          content: this.commentText
        })
        .then(result => {
          if (result.body.status === 0) {
            var addComment = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.commentText.trim()
            };
            this.commemtList.unshift(addComment);
            Toast({
              message: "评论成功",
              iconClass: "icon icon-success"
            });
            this.commentText = ""
          } else {
            Toast("评论失败");
          }
        });
    }
  },
  // 通过props属性获取父组件传输过来的数据
  props: ["id"]
};
</script>
<style lang="scss" scoped>
.comment-container {
  .title {
    color: #000;
    text-align: left;
    font-size: 18px;
  }
  textarea {
    height: 150px;
  }
  .comment-list {
    padding: 0;
    li {
      list-style: none;
      .comment-title {
        font-size: 14px;
        color: #fff;
        background: #333;
        height: 25px;
        line-height: 25px;
      }
      .comment-body {
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>

